package com.tools.cleanmaster.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

import com.tools.cleanmaster.R;
import com.nineoldandroids.view.ViewHelper;

/**
 * Created by zhangyan on 15/12/16.
 */
public class CommonRippleButton extends Button {

    private RippleView mRippleView;
    private static final int DEFAULT_RIPPLE_BACKGROUND = 0x09000000;
    private static final int DEFAULT_RIPPLE_COLOR = 0x80000000;

    public CommonRippleButton(Context context) {
        this(context, null);
    }

    public CommonRippleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CommonRippleButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    public CommonRippleButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        setWillNotDraw(false);
        mRippleView = new RippleView(this);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Ripple);
        int cornerRadius = a.getDimensionPixelSize(R.styleable.Ripple_rippleCornerRadius, 0);
        int rippleBackground = a.getColor(R.styleable.Ripple_rippleBackground, DEFAULT_RIPPLE_BACKGROUND);
        int rippleColor = a.getColor(R.styleable.Ripple_rippleColor, DEFAULT_RIPPLE_COLOR);
        mRippleView.setRippleCornerRadius(cornerRadius);
        mRippleView.setRippleBackgroud(rippleBackground);
        mRippleView.setRippleColor(rippleColor);
        a.recycle();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mRippleView.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    public final void disableRipple() {
        mRippleView.disableRipple();
    }

    public final void enableRipple() {
        mRippleView.enableRipple();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mRippleView.draw(canvas);
        super.onDraw(canvas);
    }

    @Override
    public boolean performClick() {
        if (mRippleView.isHandleable()) {
            mRippleView.onLongClick();
            return true;
        }
        return super.performClick();
    }

    public void startGuideRipple() {
        mRippleView.drawGuideRipple();
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        ViewHelper.setAlpha(this, enabled ? 1.0f : 0.4f);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mRippleView.resetSize(w, h);
    }

}
